#!/usr/bin/python

import sys
import datetime
import commands

from movie.vote.models import Movie

REVIEW_SCORE_BIN = './review-score'
ROTTEN_SCORE_BIN = './rotten-score'

def GetScore(url):
  score = commands.getoutput('%s "%s"' % (REVIEW_SCORE_BIN, url))
  print 'URL: %s Meta Score: %s' % (url, score)
  try:
    return int(score)
  except ValueError:
    return None

def GetRottenScore(movie_name):
  score = commands.getoutput('%s "%s"' % (ROTTEN_SCORE_BIN, movie_name))
  print 'Movie: %s Rotten Score: %s' % (movie_name, score)
  try:
    value = int(score)
    if value > 0:
      return value
    else:
      return None
  except ValueError:
    return None

def GetAverageScore(movie):
  if movie.rotten_score == None and movie.metacritic_score == None:
    return None
  if movie.rotten_score == None:
    return movie.metacritic_score
  elif movie.metacritic_score == None:
    return movie.rotten_score
  else:
    return (movie.rotten_score + movie.metacritic_score) / 2.0

def UpdateMovieReviewScores(old_review_days, skip_review_days):
  """old_review_days is the number of days a review score becomes stale
  and needs to be updated.

  skip_review_days is how old a movie must be before skipping updating
  reviews. This is used to stop updating review scores for very old movies
  whole scores don't change anymore.
  """
  for movie in Movie.objects.all():
    need_save = False
    now = datetime.datetime.now()
    cutoff = datetime.date.today() - datetime.timedelta(old_review_days)
    skip_cutoff = datetime.date.today() - datetime.timedelta(skip_review_days)

    if movie.rotten_url:
      if (movie.rotten_score == None or
          (movie.rotten_score_last_updated < cutoff and
           movie.date_added > skip_cutoff)):
        rotten_score = GetRottenScore(movie.name)
        if rotten_score:
          movie.rotten_score_last_updated = now
          movie.rotten_score = rotten_score
          need_save = True

    if movie.metacritic_url:
      if (movie.metacritic_score == None or
          (movie.metacritic_score_last_updated < cutoff and
           movie.date_added > skip_cutoff)):
        metacritic_score = GetScore(movie.metacritic_url)
        if metacritic_score:
          movie.metacritic_score = metacritic_score
          movie.metacritic_score_last_updated = now
          need_save = True

    average = GetAverageScore(movie) 
    if average:
      if movie.review_average_score != average:
        movie.review_average_score = average
        need_save = True

    if need_save:
      print '%s meta: %s rotten: %s average: %s' % (movie, movie.metacritic_score,
                                                    movie.rotten_score, movie.review_average_score)
      movie.save()


if __name__ == '__main__':
  days_back = 5
  skip_review_days = 30
  if len(sys.argv) > 1:
    days_back = int(sys.argv[1])
  UpdateMovieReviewScores(old_review_days=days_back, skip_review_days=skip_review_days)
